'use strict';
const sha1 = require('sha1');
const getRawBody = require('raw-body');
const URL = require('url');
const QS = require('querystring');
const Controller = require('egg').Controller;

class WechatController extends Controller {
  async server_auth() {
    const token = this.config.wechat.token; 
    const {
           signature,
           nonce,
           timestamp,
           echostr
       } = this.ctx.query;
    const str = [token,timestamp,nonce].sort().join('');
    if(sha1(str)===signature){
        this.ctx.body = echostr;
        return;
    }else{
        this.ctx.body = false;
        return;
    }
  }
  async server_listener(){
    const token = this.config.wechat.token;
    const { ctx } = this;
    const {
           signature,
           nonce,
           timestamp,
           echostr
       } = ctx.query;
    const str = [token,timestamp,nonce].sort().join('');
    if (sha1(str)!==signature){
        return;
    }
    const data = await getRawBody(ctx.req,{
        'length':ctx.length,
        'limit':'1mb',
        'encoding':ctx.charset
    });
    const wxJson = await this.ctx.helper.wechatXml2Json(data);
    const replyXML = await ctx.service.wechatMsg.replyRule(wxJson.xml);
    ctx.status = 200; 
    ctx.type = 'application/xml';
    ctx.body = replyXML;
  }
  async wechat_oauth(){
    const { ctx } = this;
    let url = ctx.query.url;
    url = decodeURIComponent(url);
    const urlObject = URL.parse(url);
    const { code } = QS.parse(urlObject.query);
    const user = await ctx.service.wechatOauth.getUserInfoByCode(code);
    ctx.body = {
      user,
    };
  }
  async wechat_redirect(){
    const { ctx } = this;
    const targetUrl = `${this.config.client.url}/oauth`;
    const scope = 'snsapi_userinfo';
    const { qa, qb } = ctx.query;
    const params = `${qa}_${qb}`;
    const redirectUrl = ctx.service.wechatOauth.getAuthorizeUrl(scope,targetUrl,params);
    ctx.redirect(redirectUrl);
  }
  async js_sdk(){
    const {ctx} = this;
    const {
        url
    } = this.ctx.request.body;
    const jsapiTicket = await ctx.service.wechat.getJsapiTicket();
    const signatureObj = ctx.helper.getJssdkSignature(url,jsapiTicket);
    const result = Object.assign({},signatureObj,{
        appid:this.config.wechat.appID
    })
    ctx.body = result;
  }
}

module.exports = WechatController;